<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Test</title>
</head>

<body>
    <div>
        <input type="file" name="file" onchange="uploadFile(this)">
    </div>
    <div>
        <pre id="ret-content"></pre>
    </div>

    <script>
        function uploadFile(t) {
            if (t.files.length <= 0) {return;}
            let fm = new FormData();  //相当于Form类的接口    一切html标签里面都有其对应的接口
            fm.append('file', t.files[0]); //相当于key —— value
            fetch('/upload', {
                method: 'POST',
                body: fm
            })
            .then(async res => {
                if (res.ok) {
                    return res.text(); //返回的是一个纯文本，是一个Promise对象
                }
                throw new Error(`${res.status} ${res.statusText}`)
            })
            .then(text => {//[[PromiseValue]]是个内部变量，外部无法得到，只能在then中获取。所以就会用到第二次then了
                let d = document.getElementById('ret-content')
                d.innerHTML = `<img src="/image/${text}" style="width:80%;height:auto;">`;
            })
            .catch(err => {
                console.error(err.message)
            })
        }
    </script>
</body>

</html>